<template>
    <div>

        <el-form :model="approvalModel" size="small" label-suffix=":" ref="detailForm" :rules="approvalRules" label-width="130px">
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span>{{$t('inventoryManagement.baseInfo')}}</span>
                </div>

                <el-row :gutter="5">
                    <el-col :span="8">
                        <el-form-item :label="$t('public.title')" prop="applyTitle">
                            <el-input v-model="approvalModel.applyTitle" clearable disabled size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('inventoryManagement.purchaser')" prop="applyer">
                            <el-input v-model="approvalModel.applyer" clearable disabled size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.applyDept')" prop="applyDept">
                            <el-input v-model="approvalModel.applyDept" clearable disabled size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.branchDept')" prop="branchDept">
                            <el-input :disabled="isCanEdit" v-model="approvalModel.branchDept" clearable  size="small" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.companyCode')" prop="companyCode">
                            <el-input :disabled="isCanEdit" v-model="approvalModel.companyCode" clearable  size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.unPassStage')" prop="unPassStage">

                            <el-select :disabled="isCanEdit" class="select-style" v-model="approvalModel.unPassStage" clearable size="small" placeholder="请选择">
                                <el-option
                                    v-for="item in dict.type.NYIQC_MRB_UNQUALIFIED_STAGE"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.applyDate')" prop="applyDateTime">
                            <el-input v-model="approvalModel.applyDateTime" clearable disabled size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item ref="applyerManageField" :label="$t('mrbForm.applyerManage')" prop="applyerManage">
                            <template slot-scope="scope">
                                <select-user-dialog :disabled="isCanEdit" v-model="approvalModel.applyerManage" @input="changeApplyerManage"/>
                            </template>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item ref="linkFileField" :label="$t('mrbForm.linkFile')" prop="linkFile">
                            <file-upload :disabled="dialogType === '3' || dialogType === '4'" v-model="approvalModel.linkFile" :limit="1" bizType="PROCESS_LINK_FILE_UPLOAD" :bizId="fileId" :otherList="processLinkFileList" @change="changeProcessFile"></file-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-card>

            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span>{{ $t('mrbForm.serviceInfo') }}</span>
                </div>
                <el-row :gutter="5">
                    <el-col :span="24">
                        <el-form-item :label="$t('mrbForm.decideWay')" prop="decideWay">
                            <el-radio-group :disabled="isCanEdit" v-model="approvalModel.decideWay">
                                <el-radio v-for="(item, key) in dict.type.NYIQC_MRB_MAKING_METHED" :key="key" :label="item.value" @change="checkDecideWay">{{ item.label }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="5" v-if="isShowDecideWay">
                    <el-col :span="8">
                        <el-form-item :label="$t('inspectionManagement.whetherTrial')" prop="isTrialInvest" >
                            <el-select :disabled="isCanEdit" class="select-style" v-model="approvalModel.isTrialInvest" clearable size="small" placeholder="请选择">
                                <el-option
                                    v-for="item in isTrialInvestList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item  :label="$t('mrbForm.isLaunchFee')" prop="isLaunchFee" >
                            <el-select :disabled="isCanEdit" class="select-style" v-model="approvalModel.isLaunchFee" clearable size="small" placeholder="请选择">
                                <el-option
                                    v-for="item in isLaunchFeeList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item ref='workshopHeadField' :label="$t('mrbForm.workshopHead')" prop="workshopHead" >
                            <template slot-scope="scope">
                                <select-user-dialog :disabled="isCanEdit" v-model="approvalModel.workshopHead" @input="changeWorkshopHead"/>
                            </template>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="approvalModel.isTrialInvest==1">
                        <el-form-item ref="trialInvestResultFileField" :label="$t('trialinvestment.trialInvestment')" prop="trialInvestResult" >
                            <file-upload :disabled="dialogType === '3'" v-model="approvalModel.trialInvestResult" :limit="1" bizType="TRIAL_INVEST_RESULT_FILE_UPLOAD" :bizId="fileId" :otherList="trialInvestResultFileList" @change="changeTrialInvestResultFile"></file-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 退货情况item -->
                <el-row :gutter="5" v-if="approvalModel.decideWay==3">
                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.moveReason')" prop="moveReason" >
                            <el-select :disabled="isCanEdit"  v-model="approvalModel.moveReason"
                            clearable size="small" placeholder="请选择">
                                <el-option v-for="item in dict.type.NYIQC_MOVEREASON"
                                    :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="5">
                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.base')" prop="base">
                            <!-- <el-input :disabled="isCanEdit" v-model="approvalModel.base" clearable size="small" /> -->
                            <el-select :disabled="isCanEdit" class="select-style" v-model="approvalModel.base" clearable size="small" placeholder="请选择">
                                <el-option
                                    v-for="item in baseoption"
                                    :key="item.baseName"
                                    :label="item.baseName"
                                    :value="item.baseName">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.workshop')" prop="workshop">
                            <el-input :disabled="isCanEdit" v-model="approvalModel.workshop" clearable size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.typeOption')" prop="typeOption" >
                            <el-select :disabled="isCanEdit" class="select-style" v-model="approvalModel.typeOption" clearable size="small" placeholder="请选择">
                                <el-option
                                    v-for="item in dict.type.NYIQC_MRB_TYPE_SELECT"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.productType')" prop="productType">
                            <el-select :disabled="isCanEdit" class="select-style" v-model="approvalModel.productType" clearable size="small" placeholder="请选择">
                                <el-option
                                    v-for="item in dict.type.NYIQC_NCR_TYPE"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.tcLevel')" prop="tcLevel">
                            <el-select :disabled="isCanEdit" class="select-style" v-model="approvalModel.tcLevel" clearable size="small" placeholder="请选择">
                                <el-option
                                    v-for="item in levelList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('bommaterial.batchNo')" prop="batchNo" >
                            <el-input v-model="approvalModel.batchNo" clearable size="small" disabled/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('inventoryManagement.inspectionBatchNo')" prop="inspectionLotMark" >
                            <el-input v-model="approvalModel.inspectionLotMark" clearable size="small" disabled/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('inspectionManagement.measuringModel')" prop="model">
                            <el-input :disabled="isCanEdit" v-model="approvalModel.model" clearable size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('bomControl.bomsupplier')"  >
                            <el-input v-model="approvalModel.supplier" clearable size="small" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('fmeaProject.customer')" prop="customer">
                            <el-input :disabled="isCanEdit" v-model="approvalModel.customer" clearable size="small" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.produceUnPassNumber')" prop="produceUnPassNumber" v-if="approvalModel.decideWay==1 || approvalModel.decideWay==2">
                            <el-input :disabled="isCanEdit" v-model="approvalModel.produceUnPassNumber" clearable size="small" placeholder="请输入"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.productPassNumber')" prop="productPassNummber"  v-if="approvalModel.decideWay==1 || approvalModel.decideWay==2">
                            <el-input :disabled="isCanEdit" v-model="approvalModel.productPassNummber" clearable size="small" placeholder="请输入"/>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.unqualifiedQuantity')" prop="unPassNumber">
                            <el-input :disabled="isCanEdit" v-model="approvalModel.unPassNumber" clearable size="small" placeholder="请输入"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.poorPercent')" prop="poorPercent">
                            <el-input :disabled="isCanEdit" v-model="approvalModel.poorPercent" clearable size="small" placeholder="请输入"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.materialStatus')" prop="materialStatus">
                            <el-select :disabled="isCanEdit" class="select-style" v-model="approvalModel.materialStatus" clearable size="small" placeholder="请选择">
                                <el-option
                                    v-for="item in dict.type.NYIQC_MRB_CURRENT_STATUS"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item :label="$t('mrbForm.poorDesc')" prop="poorDesc">
                            <el-input :disabled="isCanEdit" v-model="approvalModel.poorDesc" clearable size="small" placeholder="请输入"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item :label="$t('mrbForm.applyReason')" prop="applyReason">
                            <el-input :disabled="isCanEdit" v-model="approvalModel.applyReason" clearable size="small" placeholder="请输入"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item :label="$t('mrbForm.dangerEstimate')" prop="dangerEstimate">
                            <el-input :disabled="isCanEdit" v-model="approvalModel.dangerEstimate" clearable size="small" placeholder="请输入"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item :label="$t('optimization.prevent')" prop="preventMeasure">
                            <el-input :disabled="isCanEdit" v-model="approvalModel.preventMeasure" clearable size="small" placeholder="请输入"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('inventoryManagement.purchaseDocument')" prop="buyOrderId">
                            <el-input :disabled="isCanEdit" v-model="approvalModel.buyOrderId" clearable size="small" placeholder="请输入"/>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="8">
                        <el-form-item label="MRB流程编号" prop="ncrOrder">
                            <el-input v-model="approvalModel.processNo" clearable size="small" disabled placeholder="请输入"/>
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="8">
                        <el-form-item :label="$t('mrbForm.mrbOrder')" prop="ncrOrder">
                            <el-input v-model="approvalModel.ncrOrder" clearable size="small" disabled placeholder="请输入"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item :label="$t('mrbForm.remarkInfo')" prop="remarkInfo">
                            <el-input :disabled="isCanEdit" type="textarea" v-model="approvalModel.remarkInfo" clearable size="small" placeholder="请输入"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('inventoryManagement.uploadAttachments')">
                            <file-upload :disabled="dialogType === '3' || dialogType === '4'" :limit="1" bizType="ANNEX_FILE_UPLOAD" :bizId="fileId" :otherList="annexFileList"></file-upload>
                            <!-- <file-upload :disabled="isView" :limit="1" bizType="UPLOAD_FILE" :otherList="picFile" :bizId="id" v-model="viewModel.uploadAttachments" @change="(fileList)=>picChange(fileList)"></file-upload> -->
                        </el-form-item>
                    </el-col>
                </el-row>

              <!--          签核流程-->
              <process-workflow v-if="dialogType != '4'" v-model="approvalModel" :type="dialogType" :rules="approvalRules"></process-workflow>

            </el-card>
        <template>
            <!-- 审批设置 -->
            <!-- <el-card class="box-card" >
                <div slot="header" class="clearfix">
                    <span>审批设置</span>
                </div>
                <el-row :gutter="15" class="pt5">
                    <el-col :span="6" >
                        <el-form-item label="一级审批" prop="nodeNum">
                            <el-input v-model="approvalModel.nodeNum" />
                        </el-form-item>
                        <el-form-item label="一级审批" prop="approverDto.user01List" ref="user01List">
                        <enjoy-select-user v-model="viewModel.approverDto.user01List" :multiple="true" ></enjoy-select-user>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-card>
             -->
            <!-- 审核意见汇总 -->
            <el-card class="box-card" v-if="dialogType != '1'">
                <div slot="header" class="clearfix">
                    <span>{{ $t('mrbForm.approvalideaSylloge') }}</span>
                </div>
                <el-row :gutter="15" class="pt5">
                <el-table height="150px" border  :data="opinionList">
                    <!--          序号-->
                    <el-table-column :label="$t('public.serialNum')" type="index" width="55" align="center" />
                    <!--          部门-->
                    <el-table-column :label="$t('team.department')" prop="userDept"  show-overflow-tooltip />
                    <!--          审批人-->
                    <el-table-column :label="$t('task.checkman')" prop="userName"  show-overflow-tooltip />

                    <!--          审批状态-->
                    <el-table-column :label="$t('inventoryManagement.approvalStatus')" prop="operationType"  show-overflow-tooltip >
                        <template slot-scope="scope">
                            {{    operaTypeFilter(scope.row.operationType) }}
                        </template>
                    </el-table-column>
                    <!--          审批意见-->
                    <el-table-column :label="$t('backlog.approvalidea')" prop="message"  show-overflow-tooltip />
                    <el-table-column :label="$t('fmeaDoc.log.operateTime')" prop="createTime"  show-overflow-tooltip />

                </el-table>
                </el-row>
            </el-card>
            <!-- 审批 -->
            <el-card class="box-card" v-if="dialogType == '4'">
                <div slot="header" class="clearfix">
                    <span>{{ $t('home.approve') }}</span>
                </div>
                <el-form :model="auditModel" size="small" label-suffix=":"  ref="auditForm" :rules="auditRules" label-width="110px">
                    <el-row :gutter="15" >
                        <el-col :span="24" >
                        <el-form-item :label="$t('inventoryManagement.approvalStatus')" prop="relateData.passFlag">
                            <el-radio-group v-model="auditModel.relateData.passFlag">
                            <el-radio :key="item" :label="item" v-for="(item,idx) in  [1,0] ">{{
                                ['同意','不同意'][idx]
                                }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        </el-col>
                <el-col :span="24">
                    <el-form-item :label="$t('backlog.approvalidea')" prop="approvalMsg">
                    <el-input type="textarea" :placeholder="
                        $t('public.placeholder', {
                        placeholder: $t('inventoryManagement.rejectReason'),
                        })
                    " v-model="auditModel.approvalMsg" maxlength="1000" :autosize="{ minRows: 5, maxRows: 6 }">
                    </el-input>

                    </el-form-item>
                </el-col>

                </el-row>
                </el-form>
            </el-card>
        </template>
            <!-- 底部按钮 -->
            <div class="button-box">
                <!-- <el-button type="primary" @click="submitForm" :loading="loading" icon="el-icon-document" size="small" v-if="operateType!=='view'&&processCode==='0'">{{$t('public.submit')}}</el-button> -->
                <el-button type="default" icon="el-icon-close" size="small" @click="handleConfirm">{{ $t("btn.close") }}</el-button>
                <el-button type="primary" @click="saveStorage" :loading="loading" icon="el-icon-receiving" size="small"  v-if="dialogType === '1'" >{{$t('public.saveStorage')}}</el-button>
                <el-button type="primary" @click="submitForm" :loading="loading" icon="el-icon-document" size="small" v-if="dialogType === '1'">{{$t('public.submit')}}</el-button>
                <!-- 审批按钮 -->
                <el-button type="primary" @click="submitApprovalForm" :loading="loading" icon="el-icon-document" size="small" v-if="dialogType === '4'">{{$t('inventoryManagement.approval')}}</el-button>
                
                <!-- <el-button type="primary" @click="submitCostForm" :loading="loading" icon="el-icon-document" size="small">发起费用转嫁</el-button> -->

                <!-- <el-button type="primary" @click="nextStep" :loading="loading" icon="el-icon-document" size="small" v-if="operateType!=='view'&&processCode!=='0'">{{$t('public.submit')}}</el-button> -->
                <!-- <el-button size="mini" type="default" icon="el-icon-close" @click="handleConfirm" v-if="operateType==='view'" v-if="dialogType === 3">{{ $t("btn.close") }}</el-button> -->
            </div>
        </el-form>

    </div>
</template>
<script>
import {
  getNcrReviewDetail,
  ncrReviewList,
  getMrbTs,
} from '@/api/inventoryManagement/ncrReview'
import SelectUserDialog from '@/views/components/SelectUserDialog'
import { mapGetters } from 'vuex'
import moment from "moment"
import { geFileByBiz } from '@/api/file/file'
import ProcessWorkflow from './processWorkflow'
import { getOperationRecord, completTask, completTaskAfter } from '@/api/basic/activiti'
import { baseList } from '@/api/masterdata/base'
export default {
    name: 'OperateTemplate',
    dicts: [
        'NYIQC_MRB_TYPE_SELECT',
        'NYIQC_MRB_MAKING_METHED',
        'NYIQC_MRB_CURRENT_STATUS',
        'NYIQC_MRB_UNQUALIFIED_STAGE',
        'NYIQC_NCR_TYPE',
        'ACTIVITI_OPERATION_TYPE',
        'NYIQC_MOVEREASON'
    ],
    components: { SelectUserDialog,ProcessWorkflow },
    computed: {
        ...mapGetters(['userId', 'name', 'deptName']),
        isCanEdit() {
            return this.$route.query.viewType === '1' ? false:true;
        },
        // 审批意见检验规则
        auditRules() {
            const { passFlag } = this.auditModel?.relateData || {}
            return {
                ["relateData.passFlag"]: [
                    {
                    required: true,
                    message: '审批结果不能为空',
                    trigger: 'change',
                    },
                ],
                approvalMsg: [
                    { required:  passFlag == 1?false:true, message: '审批意见不能为空', trigger: 'change', },
                ],
            }
        },
    },
    data() {
        return {
            buttongo:false,
            baseoption:[],
            dialogType: 1, //1:新增  2：编辑 3：查看
            // 遮罩层
            loading: false,
            approvalModel: {
                applyTitle: '',
                applyer: '',
                applyDept: '',
                branchDept: '',
                companyCode: '',
                unPassStage: '',
                applyDateTime: '',
                applyerManage: '',
                isTrialInvest: null,
                isLaunchFee: null,
                workshopHead: '',
                decideWay: null,
                base: null,
                workshop: '',
                typeOption: null,
                productType: null,
                tcLevel: '',
                batchNo: '',
                model: '',
                supplier: '',
                customer: '',
                produceUnPassNumber: '',
                productPassNummber: '',
                unPassNumber: '',
                poorPercent: '',
                materialStatus: null,
                poorDesc: '',
                applyReason: '',
                dangerEstimate: '',
                preventMeasure: '',
                buyOrderId: '',
                processNo: '',
                ncrOrder: '',
                ncrOrder:'',
                remarkInfo: '',
                linkFile: '',
                approvalModel: '',
                trialInvestResult: '',
                annexFile: '',
                moveReason: null,
            },
            approvalRules: {
              nodeNum: [
                    {
                        required: true,
                        message: '签核流程不能为空',
                        trigger: 'change',
                    },
                ],
              userList: [
                    {
                        required: true,
                        trigger: 'change',
                    },
                ],
                applyTitle: [
                    {
                        required: true,
                        message: '标题不能为空',
                        trigger: 'blur',
                    },
                ],
                applyer: [
                    {
                        required: true,
                        message: '申请人不能为空',
                        trigger: 'blur',
                    },
                ],
                applyDept: [
                    {
                        required: true,
                        message: '申请部门不能为空',
                        trigger: 'blur',
                    },
                ],
                companyCode: [
                    {
                        required: true,
                        message: '公司代码不能为空',
                        trigger: 'blur',
                    },
                ],
                applyDateTime: [
                    {
                        required: true,
                        message: '申请日期不能为空',
                        trigger: 'blur',
                    },
                ],
                applyerManage: [
                    {
                        required: true,
                        message: '申请人经理不能为空',
                        trigger: 'change',
                    },
                ],
                linkFile: [
                    {
                        required: true,
                        message: '流程填写关联文件不能为空',
                        trigger: 'change',
                    },
                ],
                decideWay: [
                    {
                        required: true,
                        message: '决策方式不能为空',
                        trigger: 'change',
                    },
                ],
                isTrialInvest: [
                    {
                        required: true,
                        message: '是否试投不能为空',
                        trigger: 'change',
                    },
                ],
                trialInvestResult: [
                    {
                        required: true,
                        message: '试投结果不能为空',
                        trigger: 'blur',
                    },
                ],
                isLaunchFee: [
                    {
                        required: true,
                        message: '是否发起费用转嫁不能为空',
                        trigger: 'change',
                    },
                ],
                workshopHead: [
                    {
                        required: true,
                        message: '车间负责人不能为空',
                        trigger: 'change',
                    },
                ],
                base: [
                    {
                        required: true,
                        message: '所属基地不能为空',
                        trigger: 'change',
                    },
                ],
                moveReason: [
                    {
                        required: true,
                        message: '移动原因不能为空',
                        trigger: 'change',
                    },
                ],
                typeOption: [
                    {
                        required: true,
                        message: 'MRB类型选择不能为空',
                        trigger: 'change',
                    },
                ],
                productType: [
                    {
                        required: true,
                        message: '*不能为空',
                        trigger: 'change',
                    },
                ],
                // batchNo: [
                //     {
                //         required: true,
                //         message: '批次号不能为空',
                //         trigger: 'blur',
                //     },
                // ],
                model: [
                    {
                        required: true,
                        message: '规格型号不能为空',
                        trigger: 'blur',
                    }
                ],
                supplier: [
                    {
                        required: true,
                        message: '供应商不能为空',
                        trigger: 'blur',
                    }
                ],
                // customer: [
                //     {
                //         required: true,
                //         message: '客户不能为空',
                //         trigger: 'blur',
                //     }
                // ],
                // produceUnPassNumber: [
                //     {
                //         required: true,
                //         message: '制程不合格折合数量不能为空',
                //         trigger: 'blur',
                //     }
                // ],
                // productPassNummber: [
                //     {
                //         required: true,
                //         message: '来料折合数量不能为空',
                //         trigger: 'blur',
                //     }
                // ],
                // unPassNumber: [
                //     {
                //         required: true,
                //         message: '不合格数量不能为空',
                //         trigger: 'blur',
                //     }
                // ],
                poorPercent: [
                    {
                        required: true,
                        message: '不良率不能为空',
                        trigger: 'blur',
                    }
                ],
                poorDesc: [
                    {
                        required: true,
                        message: '不良描述不能为空',
                        trigger: 'blur',
                    }
                ],
                applyReason: [
                    {
                        required: true,
                        message: '申请特采原因不能为空',
                        trigger: 'blur',
                    }
                ],
                preventMeasure: [
                    {
                        required: true,
                        message: '预防措施不能为空',
                        trigger: 'blur',
                    }
                ]
            },
            isViewAnnex: false,
            fileId: '',
            checkFile: [],
            unPassStageList: [],
            isTrialInvestList: [
                {
                    label: '是',
                    value: '1'
                },
                {
                    label: '否',
                    value: '0'
                }
            ],
            isLaunchFeeList:[
                {
                    label: '是',
                    value: '1'
                },
                {
                    label: '否',
                    value: '0'
                }
            ],
            levelList: [
                {
                    label: 'A',
                    value: '0'
                },
                {
                    label: 'B',
                    value: '1'
                }
            ],
            isShowDecideWay: false,
            processLinkFileList: [],
            trialInvestResultFileList: [],
            annexFileList: [],

            // 审批表单
            auditModel:{relateData:{}},
            opinionList:[], // 审批意见总汇

            source: '', // 页面路径源 OA：从OA跳转过来的
        }
    },
    filters:{
        // operaTypeFilter:(val)=>{
        //     const res = this.dict.type.ACTIVITI_OPERATION_TYPE.find(i=>i.value == val)
        //     return res?res.label:val
        // }
    },
    beforeRouteLeave(to, from, next) {
        console.log(to, from, next);

        if(from.query?.viewType==1 && !this.buttongo){
            this.saveStorage()
        }
        next();

    },
    methods: {
        submitCostForm(){
            var data={
                mrbOrder:this.approvalModel.ncrOrder,
                lot:this.approvalModel.batchNo,//批次号:
                inspectionLotMark:this.approvalModel.inspectionLotMark,//检验批号
                customerName:this.approvalModel.customer,//客户名称

            }
            window.history.pushState(data,'', '/ny-iqc/costShift/costForm/0')
        },
        operaTypeFilter(e) {
            if (e) {
                let obj = this.dict.type.ACTIVITI_OPERATION_TYPE.find((item) => {
                    return item.value === e
                })
                if (obj) {
                    return obj.label
                } else {
                    return ''
                }
            } else {
                return ''
            }
        },
        // 清空内容
        changeApplyerManage() {
            this.$refs.applyerManageField.clearValidate();
        },

        changeWorkshopHead() {
            this.$refs.workshopHeadField.clearValidate();
        },

        // 选择文件
        changeProcessFile(fileList) {
            this.approvalModel = {
                ...this.approvalModel,
                linkFile: fileList
            };
            this.$refs.linkFileField.clearValidate();
        },

        changeTrialInvestResultFile(fileList) {
            this.approvalModel = {
                ...this.approvalModel,
                trialInvestResult: fileList
            };
            this.$refs.trialInvestResultFileField.clearValidate();
        },

        // 获取文件
        geFileByBiz(id) {
            geFileByBiz({ bizId: id }).then((res) => {
                res.data.forEach((io) => {
                    let pLen = this.processLinkFileList.length;
                    let tLen = this.trialInvestResultFileList.length;
                    let aLen = this.annexFileList.length;

                    if (io.bizType === 'PROCESS_LINK_FILE_UPLOAD' && pLen === 0) {
                        this.processLinkFileList.push(io);
                    }
                    if (io.bizType === 'TRIAL_INVEST_RESULT_FILE_UPLOAD' && tLen === 0) {
                        this.trialInvestResultFileList.push(io);
                    }
                    if (io.bizType === 'ANNEX_FILE_UPLOAD' && aLen === 0) {
                        this.annexFileList.push(io);
                    }
                })

                this.approvalModel = {
                    ...this.approvalModel,
                    linkFile: this.processLinkFileList,
                    trialInvestResult: this.trialInvestResultFileList,
                    annexFile: this.annexFileList
                }
            })

        },

        // 选择决策方式
        checkDecideWay(val) {
            if(val === '1') {
                this.isShowDecideWay = true;
            } else {
                this.isShowDecideWay = false;
            }
            this.approvalModel = {
                ...this.approvalModel,
                isTrialInvest: null,
                isLaunchFee: null,
                workshopHead: '',
                trialInvestResult: ''
            }
            this.trialInvestResultFileList = [];
        },

        // 返回
        handleConfirm() {
            if(this.source == 'OA') return window.location.href='https://oatest.jinkosolar.com/workflow/request/ViewRequestOS.jsp?reflush=1';
            this.$router.back();
        },

        // 提交mrb
        submitForm() {
            this.$refs['detailForm'].validate(valid => {
              const { applyTitle,applyer, applyDept, branchDept, companyCode, unPassStage, applyDateTime,
                applyerManage, isTrialInvest, isLaunchFee, workshopHead, decideWay, base, workshop,
                typeOption, productType, tcLevel, batchNo, model, supplier, customer, processNo,ncrOrder, produceUnPassNumber,
                productPassNummber, unPassNumber, poorPercent, materialStatus, poorDesc, applyReason,
                dangerEstimate, preventMeasure, buyOrderId, remarkInfo,processConfigList,moveReason,inspectionLotMark
              } = this.approvalModel;
              const submitParams = {
                ...this.approvalModel,
                ...((processConfigList && processConfigList.length) ?
                  {approverDto: Object.fromEntries(processConfigList.map((item,index) => [`user0${index+1}List`, item.userList.map(i=>i.id)]))} : {}),   //审批人员
                title: applyTitle,
                initiatorName: applyer,
                initiatorDept: applyDept,
                initiatorDivision: branchDept,
                companyCode: companyCode,
                unqualifiedMrbStage: unPassStage,
                initiatorTime: applyDateTime,
                applicantManager: applyerManage,
                isTrial: isTrialInvest,
                isCostTransfer: isLaunchFee,
                workshopLeader: workshopHead,
                decisionMakingMethod: decideWay,
                usingDecision: decideWay,
                base: base,
                workshop: workshop,
                mrbTypeSelect: typeOption,
                ncrType: productType,
                tcLevel: tcLevel,
                lot: batchNo,
                inspectionLotMark: batchNo,
                specificationModel: model,
                supplierName: supplier,
                customer: customer,
                onlineUnqualified: produceUnPassNumber,
                qualifiedProductNum: productPassNummber,
                unqualifiedNum: unPassNumber,
                badRate: poorPercent,
                currentStatus: materialStatus,
                badDescription: poorDesc,
                applyReason: applyReason,
                riskEvaluation: dangerEstimate,
                preventiveMeasure: preventMeasure,
                purchaseOrderNo: buyOrderId,
                ncrProcessId: processNo,
                ncrOrder,
                mrbRemark: remarkInfo,
                ncrStatus: '3',
                moveReason:moveReason,
                inspectionLotMark
              }
              // 将信息保存到额外字段中
              let extendedData = {
                nodeNum: submitParams.nodeNum,
                processConfigList:submitParams.processConfigList
              }
              submitParams.extendedData = JSON.stringify(extendedData)
                if(valid) {
                    this.loading = true;
                    ncrReviewList(submitParams).then((response) => {
                        this.buttongo=true
                        this.$modal.msgSuccess('提交成功')
                        this.$refs.detailForm.resetFields();
                        this.loading = false;
                        this.$router.back();
                    }).catch(err => {
                        this.loading = false;
                    })
                }else{
                    this.$nextTick(() => {
                        let isError = document.getElementsByClassName('is-error')
                        isError[0]?.scrollIntoView({
                            // 滚动到指定节点
                            // 值有start,center,end，nearest，当前显示在视图区域中间
                            block: 'start',
                            // 值有auto、instant,smooth，缓动动画（当前是慢速的）
                            behavior: 'smooth',
                        })
                    })
                }
            })

        },
        // 暂存mrb
        saveStorage(){
            this.buttongo=true
            this.$refs['detailForm'].validate(valid => {
              const { applyTitle,applyer, applyDept, branchDept, companyCode, unPassStage, applyDateTime,
                applyerManage, isTrialInvest, isLaunchFee, workshopHead, decideWay, base, workshop,
                typeOption, productType, tcLevel, batchNo, model, supplier, customer, processNo, ncrOrder, produceUnPassNumber,
                productPassNummber, unPassNumber, poorPercent, materialStatus, poorDesc, applyReason,
                dangerEstimate, preventMeasure, buyOrderId, remarkInfo,processConfigList,moveReason,inspectionLotMark
              } = this.approvalModel;
              const submitParams = {
                ...this.approvalModel,
                ...((processConfigList && processConfigList.length) ?
                  {approverDto: Object.fromEntries(processConfigList.map((item,index) => [`user0${index+1}List`, item.userList.map(i=>i.id)]))} : {}),   //审批人员
                title: applyTitle,
                initiatorName: applyer,
                initiatorDept: applyDept,
                initiatorDivision: branchDept,
                companyCode: companyCode,
                unqualifiedMrbStage: unPassStage,
                initiatorTime: applyDateTime,
                applicantManager: applyerManage,
                isTrial: isTrialInvest,
                isCostTransfer: isLaunchFee,
                workshopLeader: workshopHead,
                decisionMakingMethod: decideWay,
                usingDecision: decideWay,
                base: base,
                workshop: workshop,
                mrbTypeSelect: typeOption,
                ncrType: productType,
                tcLevel: tcLevel,
                lot: batchNo,
                inspectionLotMark: inspectionLotMark,
                specificationModel: model,
                supplierName: supplier,
                customer: customer,
                onlineUnqualified: produceUnPassNumber,
                qualifiedProductNum: productPassNummber,
                unqualifiedNum: unPassNumber,
                badRate: poorPercent,
                currentStatus: materialStatus,
                badDescription: poorDesc,
                applyReason: applyReason,
                riskEvaluation: dangerEstimate,
                preventiveMeasure: preventMeasure,
                purchaseOrderNo: buyOrderId,
                ncrProcessId: processNo,
                ncrOrder,
                mrbRemark: remarkInfo,
                ncrStatus: '3',
                moveReason:moveReason
              }
              // 将信息保存到额外字段中
              let extendedData = {
                nodeNum: submitParams.nodeNum,
                processConfigList:submitParams.processConfigList
              }
              submitParams.extendedData = JSON.stringify(extendedData)
              // 取消暂存校验
                if(valid || true) {
                    this.loading = true;
                    getMrbTs(submitParams).then((response) => {
                        if(response.code !== 200) return this.$modal.msgError(response.msg)
                        this.$modal.msgSuccess('已提交暂存')
                        this.$refs.detailForm.resetFields();
                        this.loading = false;
                        this.$router.back();
                    }).catch(err => {
                        this.loading = false;
                    })
                }
            })
        },

        // 提交审批
        submitApprovalForm(){
            let validRes;
            this.$refs["auditForm"].validate(valid => validRes = valid)
            if(!validRes)  return

            const params = {
              assignee: this.userId,
              assigneeName: this.name,
              assigneeDept: this.deptName,
              // 默认从路由中获取taskId
              taskId: this.$route.query.taskId??this.opinionList[0]?.taskId,
              processInstanceId: this.approvalModel.ncrProcessId,
              ...this.auditModel
            }
            //  键值映射 relateData => operationType  [1,0] => [2,3]
            params.relateData.operationType =  params.relateData?.passFlag == 1? 2:3
            completTask(params).then(res=>{
              if(res.code == 200){
                var data={
                    ncrReviewId:this.fileId,
                    type:params.relateData.operationType ==3 ? 2 :1,//1通过2不通过 
                    usingDecision:this.approvalModel.decideWay//
                }
                completTaskAfter(data).then(res=>{})
                this.$modal.alertSuccess('审批提交成功！')
                this.handleConfirm()
              }
            })
        },

        // 页面初始化
        init() {
            this.fileId = this.$route.params.id;
            this.dialogType = this.$route.query.viewType;
            this.source =  this.$route.query.source
            this.getMrbInfo(this.fileId)
        },
        // mrb详情
        getMrbInfo(id) {
            getNcrReviewDetail(id).then((response) => {
                const {
                    lot, ncrOrder, supplierName,
                    title,
                    initiatorName,
                    initiatorDept,
                    initiatorTime,
                    initiatorDivision,
                    companyCode,
                    unqualifiedMrbStage,
                    applicantManager,
                    isTrial,
                    isCostTransfer,
                    workshopLeader,
                    decisionMakingMethod,
                    // usingDecision,
                    base,
                    workshop,
                    mrbTypeSelect,
                    ncrType,
                    tcLevel,
                    inspectionLotMark,
                    specificationModel,
                    customer,
                    onlineUnqualified,
                    qualifiedProductNum,
                    unqualifiedNum,
                    badRate,
                    currentStatus,
                    badDescription,
                    applyReason,
                    riskEvaluation,
                    preventiveMeasure,
                    purchaseOrderNo,
                    ncrProcessId,
                    mrbRemark,
                    moveReason,
                    extendedData
                } = response.data;
                const datetime = moment(new Date()).format('YYYY-MM-DD');
                const applyName = this.name;
                const isAdd = this.dialogType === '1' ? true: false;
                const applyTitle = isAdd ? `JK-MRB评审流程-${applyName}-${datetime}`:title;
                const applyer =  isAdd ? applyName:initiatorName;
                const applyDept = isAdd ? this.deptName:initiatorDept;
                const applyDate = isAdd ? datetime:initiatorTime;


                const extendedDataObj = JSON.parse(extendedData)
                this.approvalModel = {
                    ...response.data,
                    applyTitle,
                    applyer,
                    applyDept,
                    applyDateTime: applyDate,
                    batchNo: lot,
                    supplier: supplierName,
                    processNo: ncrProcessId,
                    branchDept: initiatorDivision,
                    companyCode: companyCode,
                    unPassStage: unqualifiedMrbStage,
                    applyerManage: applicantManager,
                    isTrialInvest: isTrial,
                    isLaunchFee: isCostTransfer,
                    workshopHead: workshopLeader,
                    decideWay: decisionMakingMethod,
                    base: base,
                    workshop: workshop,
                    typeOption: mrbTypeSelect,
                    productType: ncrType,
                    tcLevel: tcLevel,
                    model: specificationModel,
                    customer: customer,
                    produceUnPassNumber: onlineUnqualified,
                    productPassNummber: qualifiedProductNum,
                    unPassNumber: unqualifiedNum,
                    poorPercent: badRate,
                    materialStatus: currentStatus,
                    poorDesc: badDescription,
                    applyReason: applyReason,
                    dangerEstimate: riskEvaluation,
                    preventMeasure: preventiveMeasure,
                    buyOrderId: purchaseOrderNo,
                    remarkInfo: mrbRemark,
                    moveReason:moveReason,
                    inspectionLotMark,
                    nodeNum: extendedDataObj?.nodeNum,
                    processConfigList: extendedDataObj?.processConfigList
                }

                if(this.approvalModel.decideWay === '1') {
                    this.isShowDecideWay = true;
                } else {
                    this.isShowDecideWay = false;
                }

                this.geFileByBiz(id);

                //查询流程操作记录
                if(this.approvalModel?.ncrProcessId ) {
                    getOperationRecord(this.approvalModel?.ncrProcessId).then(res=>{
                        this.opinionList = res.data
                    })
                }

            })
        },

    },
    mounted() {
        this.init();

    },
    created(){
        baseList({pageSize: 1000}).then(res=>{
            this.baseoption=res.rows
        })
    }
}
</script>
<style lang="scss" scoped>
.button-box {
    padding: 10px 0px;
    text-align: center;
    background: rgb(255, 255, 255);
    box-shadow: rgba(0, 0, 0, 0.08) 0px 2px 6px 0px;
    border-radius: 4px;
    text-align: center;
}

::v-deep .el-upload__tip {
    line-height: 20px;
}
::v-deep .el-card {
    // padding-top: 20px;
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
    padding-bottom: 20px;
}
::v-deep .el-aside {
    padding: 0;
    margin-bottom: 0;
}
.content-style {
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 2px;
    background-color: white;
    margin-top: 10px;
}
::v-deep .el-button-group .selBtn {
    background: #fff;
    border: 1px solid #0b7be3;
    color: #0b7be3;
}
::v-deep .el-button-group .unselBtn {
    background: #fff;
    border: 1px solid #ededf2;
    color: #666666;
}
.header-left {
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
    padding: 3px 0 10px;
    display: inline-flex;
    justify-content: center;
    border-bottom: 2px solid #0b7be3;
}
.header-right {
    float: right;
}
.container-header {
    border-bottom: 1px solid #ededf2;
}
.container-table {
    float: left;
    //margin-top:6px;
    width: 100%;
}
.mb8 {
    float: left;
    margin-top: 6px;
    width: 100%;
}
.drawer-footer {
    display: flex;
    position: relative;
    z-index: 9999;
    bottom: -40px;
    height: 40px;
    justify-content: center;
    width: 100%;
}
.drawer-close {
    background: #f7f8fa;
    border-color: #f7f8fa;
}

.right-btns ::v-deep .el-button {
    margin-top: 0;
}
.app-container {
    padding: 0;
}
.table-action-wrap {
    padding: 12px 0;
}
::v-deep .rowHighLight {
    background: oldlace;
}
::v-deep .el-dialog__body {
    max-height: 500px;
    overflow-y: auto;
}

.select-style {
    width: 100%;
}
.box-card{
    margin-bottom: 15px;
}
</style>
